import sys
sys.path.append("../")

from model.CommonDb import *
import requests
import datetime

class ServerMonitorController:
    def __init__(self,args):
        self.args = args
        self.table = "server_monitor"
        self.today = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    def run(self):
        if self.args["func"] == "getColumns":
            return self.getAllColumns(self.args["fields"])
        elif self.args["func"] == "getMap":
            return self.getMap(self.args["fields"])
        elif self.args["func"] == "getData":
            return self.getData(self.args["fields"],self.args["page"],self.args["num"],self.args["orderfield"],self.args["asc"])
        elif self.args["func"] == "getRowData":
            return self.getRowData(self.args["fields"], self.args["id"])
        elif self.args["func"] == "execMonitor":
            return self.execMonitor(self.args["server_id"],self.args["server_ip"])

    def getAllColumns(self,fields):
        db = CommonDb(self.table)
        rs = db.getAllColumns(fields)
        columns = []
        for row in rs:
            option = {'field': row["field"], 'title': row["comment"], 'sort': 'true', 'fixed': 'left'}
            columns.append(option)
        return columns

    def getMap(self,fields):
        db = CommonDb(self.table)
        rs = db.getAllColumns(fields)
        map = {}
        for row in rs:
            map[row["field"]] = {"title":row["comment"],"type":row["type"]}
        return map


    def getData(self,fields,page,num,orderfield,asc):
        db = CommonDb(self.table)
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        rs = db.getPageData(fieldstr[0:-1],"1",page,num,orderfield,asc)
        return rs

    def getRowData(self,fields,id):
        columns = self.getMap(fields)
        print(columns)
        db = CommonDb(self.table)
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        rs = db.getRowData(fieldstr[0:-1]," id="+id)

        return rs

    def execMonitor(self,serverId,serverIp):
        db = CommonDb(self.table)
        response = requests.get("http://" + serverIp + ":10961")
        data = response.json()
        info = {
            "server_id":serverId,
            "count_time":self.today,
            "cpu":float(data["data"]["cpu"]),
            "mem":round((float(data["data"]["mem"]["used"])*100)/float(data["data"]["mem"]["total"]),2),
            "disk":5
        }
        print(db.add(info))